package com.cleaningcloud.erp.service.impl;

import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.UniqueIdUtils;
import com.cleaningcloud.common.security.utils.CommunityTypeConversionUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.domain.ErpCommodityStockAlter;
import com.cleaningcloud.erp.api.domain.ErpWareCommodityNumber;
import com.cleaningcloud.erp.api.utils.StockCommodityAlterUtils;
import com.cleaningcloud.erp.domain.ErpWareCheck;
import com.cleaningcloud.erp.domain.ErpWareCheckDetails;
import com.cleaningcloud.erp.domain.ErpWareOverflowDetails;
import com.cleaningcloud.erp.domain.ErpWareReportingDetails;
import com.cleaningcloud.erp.domain.dto.ErpWareCheckDto;
import com.cleaningcloud.erp.domain.dto.ErpWareOverflowDto;
import com.cleaningcloud.erp.domain.dto.ErpWareReportingDto;
import com.cleaningcloud.erp.domain.vo.ErpWareCheckDetailsVo;
import com.cleaningcloud.erp.domain.vo.ErpWareCheckVo;
import com.cleaningcloud.erp.mapper.ErpCommodityStockAlterMapper;
import com.cleaningcloud.erp.mapper.ErpWareCheckMapper;
import com.cleaningcloud.erp.mapper.ErpWareCommodityNumberMapper;
import com.cleaningcloud.erp.service.IErpWareCheckService;
import com.cleaningcloud.erp.service.IErpWareOverflowService;
import com.cleaningcloud.erp.service.IErpWareReportingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 库存盘点Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-10-08
 */
@Service
public class ErpWareCheckServiceImpl implements IErpWareCheckService {
    @Autowired
    private ErpWareCheckMapper erpWareCheckMapper;

    @Autowired
    private ErpWareCommodityNumberMapper erpWareCommodityNumberMapper;

    @Autowired
    private IErpWareReportingService wareReportingService;

    @Autowired
    private IErpWareOverflowService wareOverflowService;

    @Autowired
    private ErpCommodityStockAlterMapper erpCommodityStockAlterMapper;

    /**
     * 查询库存盘点
     *
     * @param wareCheckId 库存盘点主键
     * @return 库存盘点
     */
    @Override
    public ErpWareCheckVo selectErpWareCheckByWareCheckId(Long wareCheckId) {
        ErpWareCheckVo erpWareCheckVo = erpWareCheckMapper.selectErpWareCheckByWareCheckId(wareCheckId);
        for (ErpWareCheckDetailsVo erpWareCheckDetailsVo : erpWareCheckVo.getDetailsList()) {
            erpWareCheckDetailsVo.setCommodityType(CommunityTypeConversionUtils.conversion(erpWareCheckDetailsVo.getCommodityType()));
        }
        return erpWareCheckVo;
    }

    /**
     * 查询库存盘点列表
     *
     * @param erpWareCheck 库存盘点
     * @return 库存盘点
     */
    @Override
    public List<ErpWareCheckVo> selectErpWareCheckList(ErpWareCheck erpWareCheck) {
        return erpWareCheckMapper.selectErpWareCheckList(erpWareCheck);
    }

    /**
     * 新增库存盘点
     *
     * @param erpWareCheck 库存盘点
     * @return 结果
     */
    @Override
    @Transactional
    public int insertErpWareCheck(ErpWareCheckDto erpWareCheck) {
        erpWareCheck.setCreateTime(DateUtils.getNowDate());
        erpWareCheck.setCreateId(SecurityUtils.getUserId());
        erpWareCheck.setCreateName(SecurityUtils.getUsername());
        erpWareCheck.setFlag("Y");
        erpWareCheck.setWareCheckOdd("PD" + UniqueIdUtils.generateUniqueId());
        List<ErpWareCheckDetails> detailsList = new ArrayList<>();
        erpWareCheckMapper.insertErpWareCheck(erpWareCheck);
        return getCheckDetails(erpWareCheck, detailsList);
    }

    private int getCheckDetails(ErpWareCheckDto erpWareCheck, List<ErpWareCheckDetails> detailsList) {
        if (erpWareCheck.getDetailsList() != null && !erpWareCheck.getDetailsList().isEmpty()) {
            erpWareCheck.getDetailsList().forEach(item -> {
                if (item.getQuantityResult() != null && item.getQuantityResult() != 2) {
                    item.setWareCheckId(erpWareCheck.getWareCheckId());
                    detailsList.add(item);
                }
            });
            if (!detailsList.isEmpty()) {
                erpWareCheckMapper.batchInsertWareCheckDetails(detailsList);
            }
        }
        return 1;
    }

    /**
     * 修改库存盘点
     *
     * @param erpWareCheck 库存盘点
     * @return 结果
     */
    @Override
    @Transactional
    public int updateErpWareCheck(ErpWareCheckDto erpWareCheck) {
        erpWareCheckMapper.updateErpWareCheck(erpWareCheck);
        // 先删除库存盘点明细
        erpWareCheckMapper.deleteWareCheckDetailsByWareCheckId(erpWareCheck.getWareCheckId());
        List<ErpWareCheckDetails> detailsList = new ArrayList<>();
        return getCheckDetails(erpWareCheck, detailsList);
    }

    /**
     * 批量删除库存盘点
     *
     * @param wareCheckIds 需要删除的库存盘点主键
     * @return 结果
     */
    @Override
    public int deleteErpWareCheckByWareCheckIds(Long[] wareCheckIds) {
        return erpWareCheckMapper.deleteErpWareCheckByWareCheckIds(wareCheckIds);
    }

    /**
     * 删除库存盘点信息
     *
     * @param wareCheckId 库存盘点主键
     * @return 结果
     */
    @Override
    public int deleteErpWareCheckByWareCheckId(Long wareCheckId) {
        return erpWareCheckMapper.deleteErpWareCheckByWareCheckId(wareCheckId);
    }

    @Override
    @Transactional
    public int auditErpWareCheck(ErpWareCheck erpWareCheck) {
        ErpWareCheckVo erpWareCheckVo = erpWareCheckMapper.selectErpWareCheckByWareCheckId(erpWareCheck.getWareCheckId());
        if (erpWareCheckVo == null) {
            throw new RuntimeException("库存盘点单查询失败");
        }
        erpWareCheckVo.setApproveId(SecurityUtils.getUserId());
        erpWareCheckVo.setApproveStatus(erpWareCheck.getApproveStatus());
        erpWareCheckVo.setApproveName(SecurityUtils.getUsername());
        erpWareCheckVo.setApproveTime(DateUtils.getNowDate());
        if (erpWareCheckVo.getApproveStatus() == 2) {
            erpWareCheckVo.setRejectTime(DateUtils.getNowDate());
            erpWareCheckVo.setRejectReason(erpWareCheck.getRejectReason());
        }
        // 审核通过 根据盘点数量修改商品库存
        if (erpWareCheckVo.getApproveStatus() == 2) {
            // 商品库存信息
            ErpWareCommodityNumber query = new ErpWareCommodityNumber();
            if (erpWareCheckVo.getDetailsList() != null && !erpWareCheckVo.getDetailsList().isEmpty()) {
                // 报损单
                ErpWareReportingDto wareReportingDto = new ErpWareReportingDto();
                wareReportingDto.setWareId(erpWareCheckVo.getWareId());
                wareReportingDto.setWareReportingTime(erpWareCheckVo.getWareCheckTime());
                wareReportingDto.setWareReportingPersonId(erpWareCheckVo.getWareCheckPerson());
                wareReportingDto.setApproveStatus(1);
                wareReportingDto.setRemark("库存盘点报损生成");
                // 报溢单
                ErpWareOverflowDto wareOverflowDto = new ErpWareOverflowDto();
                wareOverflowDto.setWareId(erpWareCheckVo.getWareId());
                wareOverflowDto.setWareOverflowPersonId(erpWareCheckVo.getWareCheckPerson());
                wareOverflowDto.setWareOverflowTime(erpWareCheckVo.getWareCheckTime());
                wareOverflowDto.setApproveStatus(1);
                wareOverflowDto.setRemark("库存盘点报溢生成");
                // 报损明细
                List<ErpWareReportingDetails> detailsList = new ArrayList<>();
                // 报溢明细
                List<ErpWareOverflowDetails> overflowDetailsList = new ArrayList<>();
                erpWareCheckVo.getDetailsList().forEach(item -> {
                    // 根据商品id和调出仓库id查询对应库存数据
                    query.setWareId(erpWareCheckVo.getWareId());
                    query.setCommodityId(item.getCommodityId());
                    ErpWareCommodityNumber erpWareCommodityNumber = erpWareCommodityNumberMapper.selectByCommodityIdAndWareId(query);
                    // 根据盘点数量进行修改
                    erpWareCommodityNumber.setCommodityNumber(item.getWareCheckNumber());
                    erpWareCommodityNumberMapper.updateErpWareCommodityNumber(erpWareCommodityNumber);
                    // 库存变更数量
                    BigDecimal alterNumber = new BigDecimal("0");
                    // 类型
                    String operateType = "";
                    // 商品盘亏 生成报损单数据
                    if (item.getQuantityResult() != null) {
                        if (item.getQuantityResult() == 1) {
                            ErpWareReportingDetails erpWareReportingDetails = new ErpWareReportingDetails();
                            erpWareReportingDetails.setCommodityId(item.getCommodityId());
                            erpWareReportingDetails.setCommodityNumber(item.getQuantityNumber());
                            erpWareReportingDetails.setCommodityPrice(item.getCostPrice());
                            detailsList.add(erpWareReportingDetails);
                            alterNumber = BigDecimal.valueOf(item.getQuantityNumber()).negate();
                            operateType = "5";
                        }
                        // 商品盘盈 生成报溢单数据
                        if (item.getQuantityResult() == 0) {
                            ErpWareOverflowDetails erpWareOverflowDetails = new ErpWareOverflowDetails();
                            erpWareOverflowDetails.setCommodityId(item.getCommodityId());
                            erpWareOverflowDetails.setCommodityNumber(item.getQuantityNumber());
                            erpWareOverflowDetails.setCommodityPrice(item.getCostPrice());
                            overflowDetailsList.add(erpWareOverflowDetails);
                            alterNumber = BigDecimal.valueOf(item.getQuantityNumber());
                            operateType = "6";
                        }
                    }
                    // 新增库存商品变更记录信息
                    ErpCommodityStockAlter erpCommodityStockAlter = StockCommodityAlterUtils.AssemblyInfo(item.getCommodityId(), alterNumber, operateType, erpWareCheckVo.getWareId());
                    erpCommodityStockAlterMapper.insertErpCommodityStockAlter(erpCommodityStockAlter);
                });
                // 新增报损单
                if (!detailsList.isEmpty()) {
                    wareReportingDto.setDetailsList(detailsList);
                    wareReportingService.insertErpWareReporting(wareReportingDto);
                }
                // 新增报溢单
                if (!overflowDetailsList.isEmpty()) {
                    wareOverflowDto.setDetailsList(overflowDetailsList);
                    wareOverflowService.insertErpWareOverflow(wareOverflowDto);
                }
            }
        }
        return erpWareCheckMapper.updateErpWareCheck(erpWareCheckVo);
    }
}
